<script>
import {listPatent, addPatent, updatePatent, getPatent, delPatent} from "@/api/work/patent";
import {listPatentWinners, delPatentWinners, addPatentWinners, updatePatentWinners} from "@/api/work/patentWinners";

export default {
  name: "AddPatent",
  dicts: ['professional_title','education_backgorund','sys_user_sex', 'author_type', 'school_signature', 'work_unit', 'work_ategory', 'patent_place_of_publication', 'school_audit_status', 'patent_is_call_for_language', 'subject_category', 'patent_publisher_level', 'faculty_audit_status'],
  props: {
    queryParams: {
      type: Object,
      required: true,
      default: () => ({
        pageNum: 1,
        pageSize: 10,
        patentName: null,
        affiliatedUnit: null,
        publicationTime: null,
        workCategory: null,
        publisher: null,
        auditStatus: null,
        placeOfPublication: null,
        subjectCategoryId: null,
        firstSubject: null,
        projectSource: null,
        patentWinnersId: null,
        totalBlockCount: null,
        isCallForLanguage: null,
        schoolSignature: null,
        language: null,
        isbnNumber: null,
        cipNumber: null,
        publisherLevel: null,
        filesUrl: null,
        dataAddUserId: null,
        dataAddDate: null,
        dataSchoolAuditUserId: null,
        dataSchoolAuditDate: null,
        dataSchoolAuditStatus: null,
        dataFacultyAuditUserId: null,
        dataFacultyAuditDate: null,
        dataFacultyAuditStatus: null
      })
    },
    type: {
      type: Boolean,
      required: true,
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,

      patentId: null,

      // 选中数组
      ids: [],
      // 子表选中数据
      checkedWorkPatentWinners: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 作者人表格
      patentWinnersList: [],
      // 著作
      patentList: [],

      idList: [],
      idList1: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openDetail: false,
      // 表单参数
      form: {},
      form1: {
        filesUrl: null,
      },
      // 表单校验
      rules: {
        patentName: [
          { required: true, message: '请输入著作名称', trigger: 'blur' },
        ],
        affiliatedUnit: [
          { required: true, message: '请选择所属单位', trigger: 'blur' },
        ],
        publicationTime: [
          { required: true, message: '请选择出版时间', trigger: 'blur' },
        ],
        workCategory: [
          { required: true, message: '请选择著作类别', trigger: 'blur' },
        ],
        publisher: [
          { required: true, message: '请输入出版单位', trigger: 'blur' },
        ],
        placeOfPublication: [
          { required: true, message: '请选择出版地', trigger: 'blur' },
        ],
        totalBlockCount: [
          { required: true, message: '请输入总字数', trigger: 'change' },
          { type: 'number', message: '总字数必须为数字值'}
        ],

      }
    };
  },
  created() {
    this.form = this.queryParams;
    this.form1.filesUrl = this.queryParams.filesUrl;
    this.getList();

  },
  methods: {
    next() {
      if (this.active++ > 2) this.active = 0;
    },
    /** 查询著作列表 */
    async getList() {
      if (this.form.id) {
        listPatentWinners().then(res => {
          for (const re of res.rows) {
            if (re.workPatentId == this.form.id) {
              this.patentWinnersList.push(re);
            }
          }
        })
      }
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        patentName: null,
        affiliatedUnit: null,
        publicationTime: null,
        workCategory: null,
        publisher: null,
        auditStatus: null,
        placeOfPublication: null,
        subjectCategoryId: null,
        firstSubject: null,
        projectSource: null,
        patentWinnersId: null,
        totalBlockCount: null,
        isCallForLanguage: null,
        schoolSignature: null,
        language: null,
        isbnNumber: null,
        cipNumber: null,
        publisherLevel: null,
        filesUrl: null,
        remark: null,
        dataAddUserId: null,
        dataAddDate: null,
        dataSchoolAuditUserId: null,
        dataSchoolAuditDate: null,
        dataSchoolAuditStatus: null,
        dataFacultyAuditUserId: null,
        dataFacultyAuditDate: null,
        dataFacultyAuditStatus: null
      };
      this.patentWinnersList.push(obj);
      this.resetForm("form");
      this.patentId = null;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加著作";
    },
    /** 提交按钮 */
    async handleSubmit() {
      if (this.type) {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.patentWinnersList.length === 0) {
              this.$message.error('请添加著作人信息');
              return;
            }
            this.$refs["form1"].validate(async (valid1) => {
              if (valid1) {
                this.form.filesUrl = this.form1.filesUrl;
                this.form.userId = this.$store.state.user.id;
                this.form.dataAddUserId = this.$store.state.user.id;
                this.form.dataAddDate = new Dare();
                await addPatent(this.form)
                const pList = (await listPatent()).rows;
                const newPatentId = pList[pList.length - 1].id;

                for (const pa of this.patentWinnersList) {
                  pa.workPatentId = newPatentId;
                  await addPatentWinners(pa);
                }
                this.$message.success("新增成功")
                this.$emit('handleClose');
              }
            });
          }
        });
      } else {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.patentWinnersList.length === 0) {
              this.$message.error('请添加著作人信息');
              return;
            }
            this.$refs["form1"].validate(async (valid1) => {
              if (valid1) {
                this.form.filesUrl = this.form1.filesUrl;
                await updatePatent(this.form)

                const newPatentId = this.form.id;
                const paList = (await listPatentWinners()).rows;

                for (const wi of this.patentWinnersList) {
                  let i = 0;
                  for (const pa of paList) {

                    if (pa.workPatentId == wi.workPatentId && pa.authorName == wi.authorName) {
                      break;
                    }
                    i = i + 1;
                  }
                  if (paList.length == i) {
                    wi.workPatentId = newPatentId;
                    await addPatentWinners(wi);
                  }else{
                    await updatePatentWinners(wi);
                  }

                }

                if(this.idList1.length!=0){
                  for (const ids of this.idList1) {
                    for (const id of ids) {
                      await delPatentWinners(id);
                    }
                  }
                }
                this.$message.success("修改成功")
                this.$emit('handleClose');
              }
            });
          }
        });
      }
    },
    handleClose() {
      this.$emit('handleClose')
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除著作编号为"' + ids + '"的数据项？').then(function () {
        return delPatent(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 著作完成人序号 */
    rowWorkPatentWinnersIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 著作完成人添加按钮操作 */
    handleAddWorkPatentWinners() {
      let obj = {};
      obj.signatureOrder = "";
      obj.authorType = "";
      obj.authorName = "";
      obj.gender = "";
      obj.educationBackgorund = "";
      obj.affiliatedUnit = "";
      obj.contributionRate = "";
      obj.professionalTitle = "";
      obj.role = "";
      obj.coeditNumber = "";
      this.patentWinnersList.push(obj);
    },
    /** 著作完成人删除按钮操作 */
    handleDeleteWorkPatentWinners() {
      if (this.checkedWorkPatentWinners.length == 0) {
        this.$modal.msgError("请先选择要删除的著作完成人数据");
      } else {
        this.idList1.push(this.idList);
        const patentWinnersList = this.patentWinnersList;
        const checkedWorkPatentWinners = this.checkedWorkPatentWinners;
        this.patentWinnersList = patentWinnersList.filter(function (item) {
          return checkedWorkPatentWinners.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleWorkPatentWinnersSelectionChange(selection) {
      this.idList1 = selection.map(item => item.id)
      this.checkedWorkPatentWinners = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('work/patent/export', {
        ...this.queryParams
      }, `patent_${new Date().getTime()}.xlsx`)
    }
  }
}

</script>

<template>
  <div>
    <el-header>添加著作</el-header>
    <div class="body">
      <div class="jbxx">
        <el-card style="height: 1350px">
          <el-tag style="margin-bottom: 10px">基本信息</el-tag>
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="著作名称" prop="patentName">
                  <el-input v-model="form.patentName" placeholder="请输入著作名称" style="width: 300px"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属单位" prop="affiliatedUnit">
                  <el-select v-model="form.affiliatedUnit" placeholder="请选择学科门类" style="width: 300px">
                    <el-option
                      v-for="dict in dict.type.work_unit"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="出版时间" prop="publicationTime">
                  <el-date-picker clearable
                                  v-model="form.publicationTime"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="请选择出版时间" style="width: 300px">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="著作类别" prop="workCategory">
                  <el-select v-model="form.workCategory" placeholder="请选择著作类别" style="width: 300px">
                    <el-option
                      v-for="dict in dict.type.work_ategory"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="出版单位" prop="publisher">
                  <el-input v-model="form.publisher" placeholder="请输入出版单位" style="width: 300px"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出版地" prop="placeOfPublication">
                  <el-select v-model="form.placeOfPublication" placeholder="请选择出版地" style="width: 300px">
                    <el-option
                      v-for="dict in dict.type.patent_place_of_publication"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="学科门类" prop="subjectCategoryId">
                  <el-select v-model="form.subjectCategoryId" placeholder="请选择学科门类" style="width: 300px">
                    <el-option
                      v-for="dict in dict.type.subject_category"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="一级学科" prop="firstSubject">
                  <el-input v-model="form.firstSubject" placeholder="请输入一级学科" style="width: 300px"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="项目来源" prop="projectSource">
                  <el-input v-model="form.projectSource" placeholder="请输入项目来源" style="width: 300px"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="总字数" prop="totalBlockCount">
                  <el-input v-model="form.totalBlockCount" placeholder="请输入总字数" style="width: 300px"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="是否译成外文" prop="isCallForLanguage">
                  <el-select v-model="form.isCallForLanguage" placeholder="请选择是否译成外文" style="width: 300px">
                    <el-option
                      v-for="dict in dict.type.patent_is_call_for_language"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="学校署名" prop="schoolSignature">
                  <el-select v-model="form.schoolSignature" placeholder="请选择学校署名" style="width: 300px">
                    <el-option
                      v-for="dict in dict.type.school_signature"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="语种" prop="language">
                  <el-input v-model="form.language" placeholder="请输入语种" style="width: 300px"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="ISBN号" prop="isbnNumber">
                  <el-input v-model="form.isbnNumber" placeholder="请输入ISBN号" style="width: 300px"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="CIP号" prop="cipNumber">
                  <el-input v-model="form.cipNumber" placeholder="请输入CIP号" style="width: 300px"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出版社级别" prop="publisherLevel">
                  <el-select v-model="form.publisherLevel" placeholder="请选择出版社级别" style="width: 300px">
                    <el-option
                      v-for="dict in dict.type.patent_publisher_level"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">

              </el-col>
              <el-col :span="12">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" placeholder="请输入备注" style="width: 300px"/>
                </el-form-item>
              </el-col>
            </el-row>

            <el-tag style="margin-bottom: 10px">作者信息</el-tag>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddWorkPatentWinners">添加作者
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteWorkPatentWinners">删除
                </el-button>
              </el-col>
            </el-row>
            <el-table :data="patentWinnersList" :row-class-name="rowWorkPatentWinnersIndex"
                      @selection-change="handleWorkPatentWinnersSelectionChange" ref="workPatentWinners" :rules="rules">
              <el-table-column type="selection" width="50" align="center"/>
              <el-table-column label="序号" align="center" prop="index" width="50"/>
              <el-table-column label="署名顺序" prop="signatureOrder" width="150">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.signatureOrder" placeholder="请输入署名顺序"/>
                </template>
              </el-table-column>
              <el-table-column label="作者类型" prop="authorType" width="150">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.authorType" placeholder="请选择作者类型">
                    <el-option
                      v-for="dict in dict.type.author_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="作者姓名" prop="authorName" width="150">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.authorName" placeholder="请输入作者姓名"/>
                </template>
              </el-table-column>
              <el-table-column label="性别" prop="gender" width="150">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.gender" placeholder="请选择性别">
                    <el-option
                      v-for="dict in dict.type.sys_user_sex"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="学历" prop="educationBackgorund" width="150">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.educationBackgorund" placeholder="请选择性别">
                    <el-option
                      v-for="dict in dict.type.education_backgorund"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="工作单位" prop="affiliatedUnit" width="150">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.affiliatedUnit" placeholder="请选择性别">
                    <el-option
                      v-for="dict in dict.type.work_unit"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="贡献率 %" prop="contributionRate" width="150">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.contributionRate" placeholder="请输入贡献率 %"/>
                </template>
              </el-table-column>
              <el-table-column label="职称" prop="professionalTitle" width="150">

                <template slot-scope="scope">
                  <el-select v-model="scope.row.professionalTitle" placeholder="请选择职称">
                    <el-option
                      v-for="dict in dict.type.professional_title"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="承担角色" prop="role" width="150">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.role" placeholder="请输入承担角色"/>
                </template>
              </el-table-column>
              <el-table-column label="参编字数" prop="coeditNumber" width="150">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.coeditNumber" placeholder="请输入参编字数"/>
                </template>
              </el-table-column>
            </el-table>
            <el-tag style="margin-bottom: 30px">附件信息</el-tag>

            <el-form :model="form1" label-width="120px" :rules="rules" ref="form1">
              <el-form-item label="附件信息" prop="filesUrl">
                <file-upload v-model="form1.filesUrl" :file-size="1000"
                             :file-type="['doc','docx', 'xls','xlsx', 'ppt', 'txt', 'pdf']"/>
              </el-form-item>
            </el-form>
          </el-form>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
            <el-button @click="handleClose">取 消</el-button>
          </div>
        </el-card>
      </div>
    </div>
  </div>

</template>

<style scoped lang="scss">
.el-header, .el-footer {
  background-color: #B3C0D1;
  color: #333;
  text-align: left;
  line-height: 60px;
  font-weight: bold;
}

.body {
  width: 100%;
  height: 1300px;
  margin-bottom: 20px;
}

.jbxx {
  width: 100%;
  height: 700px;
}
.dialog-footer {
  margin-top: 50px;
  margin-left: 900px;
}
</style>
